/*
 *
 * Copyright (C) 2012 Walter Lütgenau
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * 
 */
package offset.nodes.server.core.services;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import javax.jcr.RepositoryException;
import offset.nodes.client.model.SimpleNamespaceRegistry;
import offset.nodes.client.virtual.model.jcr.nodetype.NodeTypeDefinition;
import offset.nodes.client.virtual.model.jcr.nodetype.NodeTypeReader;
import org.apache.jackrabbit.core.nodetype.NodeTypeDef;
import org.apache.jackrabbit.core.nodetype.xml.NodeTypeWriter;

/**
 *
 * @author Walter Lütgenau
 */
public class ToNodeTypeDefinitionConverter {

    /**
     * Convert a node type definition from the jackrabbit specific class to a common class in order to prevent the applet client from
     * using jackrabbit classes.
     *
     * @param nodeTypeDef
     * @return
     * @throws Exception
     */
    public static NodeTypeDefinition convert(NodeTypeDef nodeTypeDef) throws Exception {
        NodeTypeDefinition result = null;

        ByteArrayOutputStream out = new ByteArrayOutputStream();
        SimpleNamespaceRegistry namespaces = SimpleNamespaceRegistry.getInstance();
        NodeTypeDef[] nodeTypes = new NodeTypeDef[]{nodeTypeDef};

        NodeTypeWriter.write(out, nodeTypes, namespaces);
        NodeTypeDefinition[] definitions = NodeTypeReader.read(new ByteArrayInputStream(out.toByteArray()));
        if (definitions.length > 0)
            result = definitions[0];

        return result;
    }
}
